package net.java.mediasystems.web.converter;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.lang3.StringUtils;

import net.java.mediasystems.database.core.model.MediaQuality;
import net.java.mediasystems.database.core.service.MediaQualityService;

public class MediaQualityConverter implements Converter {

	private List<MediaQuality> mediaQualityList;
	
	private MediaQualityService mediaQualityService;
	
	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		if (!StringUtils.isEmpty(value)) {
			for (MediaQuality curMediaQuality : this.mediaQualityList) {
				if (curMediaQuality.getId().longValue() == Long.parseLong(value)) {
					return curMediaQuality;
				}
			}
		}
		return null;
	}
	
	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		MediaQuality mediaQuality = (MediaQuality) value;
		return mediaQuality.getId().toString();
	}
	
	/**
	 * Special Set()-Method: The MediaQualityList will be initialized immediately after setting the MediaQualityService.
	 * 
	 * @param mediaQualityService MediaQualityService
	 */
	public void setMediaQualityService(MediaQualityService mediaQualityService) {
		this.mediaQualityService = mediaQualityService;
		this.mediaQualityList = this.mediaQualityService.getAllMediaQualities();
	}
}
